package com.example.demo.AI;

import com.example.demo.entity.DTO.DialogueHistoryDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class Baichaun2_13BService {
    private static final String API_URL = "http://10.58.0.2:6677/v1/chat/completions";

    private static final String MODEL = "XXX";
    private static final Integer MAX_TOKENS = 1000;

    private static final Double TEMPERATURE = 0.5;

    private static final Double TOP_P = 1.0;

    private static final String API_KEY = "xxx";
    private static final String CONTENT_TYPE = "application/json";
    private static final String AUTHORIZATION_PREFIX = "Bearer ";


    private static final Integer TOKENS_TO_GENERATE = 1000;
    public String sendChatRequest(List<DialogueHistoryDTO> messages) {

        RestTemplate restTemplate = new RestTemplate();

        // 设置API请求的URL和请求头信息
        String url = API_URL ;
        String authorization = AUTHORIZATION_PREFIX + API_KEY;
        String contentType = CONTENT_TYPE;

        //构造请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setBearerAuth(API_KEY);
        headers.set("Content-Type", CONTENT_TYPE);

        // 构造API请求的请求体信息
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", MODEL);
        requestBody.put("max_tokens", MAX_TOKENS);
        requestBody.put("temperature", TEMPERATURE);
        requestBody.put("top_p", TOP_P);
        requestBody.put("messages", messages);

        // 创建请求实体对象
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);


        // 发送 POST 请求
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);

        System.out.println("请求："+requestEntity);

        System.out.println("响应："+responseEntity);

        // 获取响应数据
        String responseBody = responseEntity.getBody();

        System.out.println("响应体："+responseBody);

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode rootNode = objectMapper.readTree(responseBody);

            return rootNode.get("choices").get(0).get("message").get("content").asText();
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to extract answer", e);
        }

    }
}